package com.alumni_circle.core.config;

/**
 * @author 龙小虬
 * @since 2020-08-27 17:18
 */

import com.alumni_circle.core.entity.access.AccessLog;
import com.alumni_circle.core.service.access.impl.AccessLogServiceImpl;
import com.alumni_circle.core.utils.SecurityUtils;
import com.alumni_circle.core.utils.StringTime;
import org.apache.naming.factory.BeanFactory;
import org.apache.naming.factory.FactoryBase;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 *
 * @ClassName: SysLogAspect
 * @Description: 系统日志切面
 * @author 龙小虬
 * @date 2018年5月23日 下午12:00:17
 *
 */
@Aspect
@Component
@EnableAspectJAutoProxy
public class  SysLogAspect {

    @Resource
    private AccessLogServiceImpl accessLogService;

    /**
     * 注解声明切点
     */
    @Pointcut("@annotation(com.alumni_circle.core.config.SysLog)")
    public void annotationPointCut(){
    }

    /**
     * 环绕通知
     */
    @SuppressWarnings("unchecked")
    @Around("annotationPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        Object result=joinPoint.proceed();

        //保存系统日志
        this.saveSysLog(joinPoint);

        return result;
    }

    /**
     * 保存系统日志信息
     */
    private void saveSysLog(ProceedingJoinPoint joinPoint){

        AccessLog accessLog=new AccessLog();

        //获取系统日志注解，并设置操作类型和操作描述
        MethodSignature signature=(MethodSignature) joinPoint.getSignature();
        SysLog sysLog=signature.getMethod().getAnnotation(SysLog.class);
        accessLog.setAccessInfo(sysLog.accessInfo());
        accessLog.setType(sysLog.type());
        accessLog.setUrl(sysLog.url());
        accessLog.setUserId(SecurityUtils.getId());
        accessLog.setUserName(SecurityUtils.getName());
        accessLog.setCreateTime(StringTime.time());
        System.out.println("--------------------------------------------------------------------------------------");
//        try {
//            Thread.sleep(9999);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        accessLogService.save(accessLog);
    }
}
